<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @author CHUN Dany <chundany@gmail.com>
 */
class Location extends Admin_Controller
{
  function __construct()
  {
    parent::__construct();
    $this->load->model('mod_location', 'md');
  }
  
  public function view()
  {
    $uriSegment = 4;
    $perPage = 15;  
    $this->data = $this->md->getLocation(uri($uriSegment), $perPage);
    pagination_config(site_url(module_controller('view')), $this->md->getLocationNum(), $perPage, $uriSegment); // base_url, total_num, per_page, segment
    
    $this->title  = 'Location Management';
    $this->action = 'Location Management';
    $this->btnActtion = 'new';
    $this->lblActtion = 'Add New';
  }
  
  public function add()
  {
    if($this->input->post())
    {
      $this->form_validation->set_rules('name', 'Name', 'trim|xss_clean|required|max_length[45]|is_unique['.table('location').'.'.field('name').']')
                            ->set_rules('description', 'Description', 'trim|xss_clean|max_length[255]')
                            ->set_message('is_unique', 'The %s field is alreadied exists.');
        
      if ($this->form_validation->run() === TRUE)
      {
        if($this->md->insert() > 0)
        {
          successMsg('Successfully add new location!');
          redirect(module_controller('view'));
        }
        else
        {
          errorMsg('Could not add new location, please try again!');
        }
      }
    }
    
    $this->title  = 'Add New Location';
    $this->action = 'Add New Location';
  }
  
  public function edit()
  {
    $id  = $this->uri->segment(4);
    $row = $this->md->getLocationById($id);
    
    if($this->input->post())
    {
      $this->form_validation->set_rules('name', 'Name', 'trim|xss_clean|required|max_length[45]|uniqueExcept['.table('location').'.'.field('name').'.'.field('id').']')
                            ->set_rules('description', 'Description', 'trim|xss_clean|max_length[255]')
                            ->set_rules('disable', 'Disable', 'trim|xss_clean');
      
      if ($this->form_validation->run() === TRUE)
      {        
        if($this->md->update($id) > 0)
        {
          successMsg('Successfully edit location!');
          redirect(module_controller('view'));
        }
        else
        {
          errorMsg('Could not edit location, please try again!');
        }
      }
    }
    $this->row = $row;
      
    $this->title  = 'Edit Location';
    $this->action = 'Edit Location';
  }
  
  public function delete()
  {
    $id = $this->uri->segment(4);

    if ($this->md->delete($id) > 0)
    {
      successMsg('Successfully delete!');
    }
    else
    {
      errorMsg('Could not delete, please try again!');
    }
    
    redirect(module_controller('view'));
  }
}
